[LeetCode] 88. Merge Sorted Array

[LeetCode] 88. Merge Sorted Array

問題描述

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

翻譯

給定兩個排序過整數陣列,請將兩組陣列合併成一個排序過後的陣列
nums1、nums2 陣列大小分別為 m、n,你可以假定 nums1 有足夠的額外空間(空間可能是 n + m,或者更大)存放從 num2 陣列的元素。

解題思維

  1. 由於已知 num1 有足夠空間存放來自 num2 的元素,所以我們可以將 num2 元素從 num1 末端插入
  2. 重新排序

解題報告

Level: Easy
Time Complexity: O(nlog(n))
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
Memory Usage: 39.7 MB, less than 5.94% of Java online submissions for Merge Sorted Array.

程式完整解題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Arrays;
class Solution {
/**
*@param nums1 陣列一
*@param m 陣列一大小
*@param nums2 陣列二
*@param n 陣列二大小
*@return
**/
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i = m ; i < n + m ; i++)
nums1[i] = nums2[i-m];

Arrays.sort(nums1);
}
}
作者

Gordon Fang

發表於

2020-06-01

更新於

2021-06-27

許可協議

評論